package pers.xiaojun.boot.module.system.service.permission;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import pers.xiaojun.boot.common.util.CollectionUtils;
import pers.xiaojun.boot.module.system.constants.RedisKeyConstants;
import pers.xiaojun.boot.module.system.dao.mapper.permission.UserRoleMapper;
import pers.xiaojun.boot.module.system.dao.entity.permission.UserRoleDO;

import java.util.Collection;
import java.util.List;

/**
 * 用户角色服务实现
 *
 * @author xiaojun
 * @since 2025-10-10
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRoleDO> implements UserRoleService {

    @Override
    @CacheEvict(value = RedisKeyConstants.Cache.USER_ROLE_IDS, key = "#userId")
    public void saveUserRoles(Long userId, Collection<Long> roleIds) {
        this.baseMapper.insert(CollectionUtils.convertList(
                roleIds,
                roleId -> new UserRoleDO().setUserId(userId).setRoleId(roleId)
        ));
    }

    @Override
    @CacheEvict(value = RedisKeyConstants.Cache.USER_ROLE_IDS, key = "#userId")
    public void removeUserRoleByUserIdAndRoleIds(Long userId, Collection<Long> roleIds) {
        this.baseMapper.delete(new LambdaUpdateWrapper<UserRoleDO>()
                .eq(UserRoleDO::getUserId, userId)
                .in(UserRoleDO::getRoleId, roleIds)
        );
    }

    @Override
    @Cacheable(value = RedisKeyConstants.Cache.USER_ROLE_IDS, key = "#userId")
    public List<Long> listRoleIdsByUserId(Long userId) {
        return this.baseMapper.selectObjs(new LambdaQueryWrapper<UserRoleDO>()
                .select(UserRoleDO::getRoleId)
                .eq(UserRoleDO::getUserId, userId)
        );
    }

}
